package org.answer.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.answer.dao.RoleDao;
import org.answer.entity.PageResult;
import org.answer.entity.QueryPageBean;
import org.answer.pojo.Role;
import org.answer.service.RoleService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findRoleAll() {
        List<Role> roleAll = roleDao.findRoleAll();

        return roleAll;
    }


    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增角色,，同时关联权限
     * @param role
     * @param permissionIds
     */
    @Override
    public void add(Role role, Integer[] permissionIds) {
        roleDao.add(role);
        Integer roleId = role.getId();
        if(permissionIds != null && permissionIds.length > 0){
            setRoleAndPermission(roleId,permissionIds);
        }
    }

    /**
     * 删除角色信息
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //先删除关联子项
        roleDao.deleteAssocication(id);
        //在删除Role对象
        roleDao.deleteById(id);
    }

    /**
     * 根据角色id查询权限
     * @param id
     * @return
     */
    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);
    }

    /**
     * 编辑角色
     * @param role
     * @param permissionIds
     */
    @Override
    public void edit(Role role, Integer[] permissionIds) {
        //清理当前角色关联的权限，操作中间关系表t_role_permission表
        roleDao.deleteAssocication(role.getId());

        //修改角色基本信息
        roleDao.edit(role);

        //重新建立当前检查组和检查项的关联关系
        setRoleAndPermission(role.getId(),permissionIds);
    }

    /**
     * 设置角色和权限多对多的关系,操作t_role_permission
     * @param roleId
     * @param permissionIds
     */
    private void setRoleAndPermission(Integer roleId, Integer[] permissionIds) {
        for (Integer permissionId : permissionIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("role_id",roleId);
            map.put("permission_id",permissionId);
            roleDao.setRoleAndPermission(map);
        }
    }
}
